package com.stationbuilding.fragment.quality;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.stationbuilding.MyApplication;
import com.stationbuilding.R;
import com.stationbuilding.activity.quality.QualityAddActivity;
import com.stationbuilding.adapter.quality.QualityFragmentHomeListAdapter;
import com.stationbuilding.adapter.quality.QualityFragmentPagerAdapter;
import com.stationbuilding.api.RetrofitManager;
import com.stationbuilding.bean.DictListBean;
import com.stationbuilding.bean.DictBean;
import com.stationbuilding.bean.QuestionBean;
import com.stationbuilding.bean.QuestionListBean;
import com.stationbuilding.bean.ResultBean;
import com.stationbuilding.constants.Constants;
import com.stationbuilding.utils.PreferenceHelper;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MultipartBody;

public class QualityFragment extends Fragment {

    private View view;
    private ExpandableListView listView;
    private LinearLayout statisticLayout;
    private ViewPager viewPager;
    private QualityFragmentHomeListAdapter listAdapter;
    private QualityFragmentPagerAdapter pagerAdapter;
    private ProgressDialog dialog;//加载提示
    private LinearLayout emptyView;//空试图
    private List<DictBean> groupData = new ArrayList<>();
    private List<QuestionBean> itemData = new ArrayList<>();
    private List<Fragment> list = new ArrayList<>();
    private String token = PreferenceHelper.getInstance(getActivity()).getToken();
    private String expandId;
    private String selectedChildProgressStatus;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {

        // 两次点击按钮之间的点击间隔不能少于1000毫秒
        private static final int MIN_CLICK_DELAY_TIME = 1000;
        private long lastClickTime;

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            long curClickTime = System.currentTimeMillis();
            if((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
                // 超过点击间隔后再将lastClickTime重置为当前点击时间
                lastClickTime = curClickTime;
                switch (item.getItemId()) {
//                    case R.id.navigation_home:
//                        listView.setVisibility(View.VISIBLE);
//                        statisticLayout.setVisibility(View.GONE);
//                        loadGroupData();
//                        return true;
//                    case R.id.navigation_add:
//                        startActivityForResult(new Intent(getActivity(), QualityAddActivity.class), 0);
//                        return false;
//                    case R.id.navigation_statistic:
//                        listView.setVisibility(View.GONE);
//                        statisticLayout.setVisibility(View.VISIBLE);
//                        loadStatistic();
//                        return true;
                }
            }
            return false;
        }
    };

    private AdapterView.OnItemLongClickListener onItemLongClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            int longClickPosition = (int) view.getTag(R.layout.home_item);
            if (Constants.PROGRESS_STATUS_1.equals(itemData.get(longClickPosition).getProcessStatus())) {
                showDeleteDialog(longClickPosition);
            }
            return true;
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            loadItemData();
        } else {
            if (Constants.PROGRESS_STATUS_2.equals(selectedChildProgressStatus)) {
                loadItemData();
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_quality, container, false);
        BottomNavigationView bottomNavigationView = (BottomNavigationView) view.findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        init();
        return view;
    }

    /**
     * 初始化操作
     */
    private void init() {
        emptyView = (LinearLayout) view.findViewById(R.id.empty_view);
        // 首页
        listView = (ExpandableListView) view.findViewById(R.id.home_list);
        listView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                for (int i = 0; i < groupData.size(); i++) {
                    if (groupPosition != i) {
                        listView.collapseGroup(i);
                    }
                }
                expandId = groupData.get(groupPosition).getId();
                loadItemData();
            }
        });
        listView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                if (itemData != null) {
                    itemData.clear();
                    listAdapter.setItemData(itemData);
                    listAdapter.notifyDataSetChanged();
                }
            }
        });
        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Intent intent = new Intent(getActivity(), QualityAddActivity.class);
                intent.putExtra("questionId", itemData.get(childPosition).getQuestionId());
                selectedChildProgressStatus = itemData.get(childPosition).getProcessStatus();
                startActivityForResult(intent, 0);
                return false;
            }
        });
        listView.setOnItemLongClickListener(onItemLongClickListener);
        listAdapter = new QualityFragmentHomeListAdapter(MyApplication.getContext(), null, null);
        listAdapter.setGroupData(groupData);
        listView.setAdapter(listAdapter);
        loadGroupData();

        // 统计
        statisticLayout = (LinearLayout) view.findViewById(R.id.statistic);
        viewPager = (ViewPager) statisticLayout.findViewById(R.id.statistic_view_pager);
        viewPager.setOffscreenPageLimit(2);
        TabLayout tabLayout = (TabLayout) statisticLayout.findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);

        RetrofitManager.getInstance().setOnInternetListener(new RetrofitManager.OnInternetListener() {
            @Override
            public void internetListener() {
                emptyView.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 是否删除问题
     */
    private void showDeleteDialog(final int position) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme);
        alertDialog.setTitle("删除确认");
        alertDialog.setMessage("是否要删除该问题?");
        alertDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteQuestion(position);
                    }
                });
        alertDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        alertDialog.show();
    }

    private void deleteQuestion(final int position) {
        Observer<ResultBean> questionBeanSubscriber = new Observer<ResultBean>() {
            @Override
            public void onComplete() {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
            @Override
            public void onError(Throwable e) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                Toast.makeText(getActivity(), "删除数据异常，请重试", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                dialog = ProgressDialog.show(getActivity(), null, "数据删除中...");
            }
            @Override
            public void onNext(ResultBean resultBean) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                if (resultBean.getCode() == 0) {
                    Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                    itemData.remove(position);
                    listAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(getActivity(), resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        };
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.addFormDataPart("questionId", itemData.get(position).getQuestionId());
        builder.addFormDataPart("delFlag", Constants.DEL_FLG_1);
        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        RetrofitManager.toSubscribe(RetrofitManager.getApiService().updateQuestion(token, multipartBody), questionBeanSubscriber);
    }

    /**
     * 数据加载
     */
    private void loadGroupData() {
        RetrofitManager.toSubscribe(
                RetrofitManager.getApiService().getDictListByPid(token, Constants.DICT_ID_QUESTION_STATUS),
                new Observer<DictListBean>() {
                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                        dialog = ProgressDialog.show(getActivity(), null, "加载数据...");
                    }

                    @Override
                    public void onComplete() {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
//                            listView.expandGroup(0);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getActivity(), "出错", Toast.LENGTH_SHORT).show();
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onNext(DictListBean dictListBean) {
                        groupData = dictListBean.getDictList();
                        emptyView.setVisibility(View.GONE);
                        listAdapter.setGroupData(groupData);
                        listAdapter.notifyDataSetChanged();
                    }
                });
    }

    /**
     * 数据加载
     */
    private void loadItemData() {
        String initiator = null;
        if (Constants.PROGRESS_STATUS_1.equals(expandId)) {
            initiator = PreferenceHelper.getInstance(getActivity()).getUserId();
        }
        RetrofitManager.toSubscribe(
                RetrofitManager.getApiService().getQuestionListByStatus(token, expandId, Constants.QUESTION_TYPE_QUALITY, initiator),
                new Observer<QuestionListBean>() {

                    @Override
                    public void onComplete() {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getActivity(), "出错", Toast.LENGTH_SHORT).show();
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                        dialog = ProgressDialog.show(getActivity(), null, "加载数据...");
                    }

                    @Override
                    public void onNext(QuestionListBean questionListBean) {
                        itemData = questionListBean.getQuestionList();
                        emptyView.setVisibility(View.GONE);
                        listAdapter.setItemData(itemData);
                        listAdapter.notifyDataSetChanged();
                    }
                });
    }

    /**
     * 刷新统计
     */
    private void loadStatistic() {
        if (pagerAdapter != null) {
            pagerAdapter = null;
            list.clear();
        }
        list.add(new QualityFragmentStatus());
        list.add(new QualityFragmentLevel());
        list.add(new QualityFragmentScore());
        pagerAdapter = new QualityFragmentPagerAdapter(getChildFragmentManager(), list);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(0);
    }
}
